import { Database, db } from "@/api";
import { HeightUtil } from "@/util";
import { createAtom, useStore } from "@/util/hooks";
import { Table, TableColumnProps } from "@arco-design/web-react";
import { RowCallbackProps } from "@arco-design/web-react/es/Table/interface";
import { useEffect } from "react";
import { DBTableHeader } from "./header";
import { DBTableStore } from "./inteface";
import { ContextMenuRow } from "./menu";
import { DBTableModal } from "./modal";
import "./style.less";

const columns: TableColumnProps[] = [
  {
    dataIndex: "name",
    title: "数据源",
  },
];

export const DBTableAtom = createAtom<DBTableStore>({
  data: [],
});

export const DBTable = () => {
  const { value, updateStore } = useStore(DBTableAtom);

  async function queryList() {
    const res = await db.list();
    updateStore({
      data: res.data,
    });
  }

  function onRow(record: Database, index: number) {
    return {
      onClick(e) {
        const alreadySelected = value.selected?.id === record.id;
        updateStore({
          selected: alreadySelected ? undefined : record,
        });
      },
    } as RowCallbackProps;
  }

  function rowClassName(record: Database, index: number) {
    if (!value.selected) {
      return "";
    }
    return value.selected.id === record.id ? "selected" : "";
  }

  useEffect(() => {
    queryList();
  }, []);

  return (
    <div className="db-table">
      <DBTableHeader />
      <Table
        style={{ height: HeightUtil.fillHeightStyle(2) }}
        rowKey="id"
        columns={columns}
        data={value.data}
        showHeader={false}
        pagination={false}
        onRow={onRow}
        rowClassName={rowClassName}
        components={{
          body: {
            row: ContextMenuRow,
          },
        }}
      />
      <DBTableModal />
    </div>
  );
};
